/**
 * Created by hao.cheng on 2017/4/15.
 */
import React from "react";
import { Select, Table, Popconfirm, Button, Switch, Modal, Form, Upload, Icon, InputNumber } from "antd";
import { get } from "@/axios/tools";
import { connect } from "react-redux";
import SetMealForm from "@/components/form/setMealForm"
const PLACEHOLDER_IMG = require('@/asset/placeholder_sm.jpg');
const Option = Select.Option;
const DEFAULT_SIZE = 10;

class SelectFoodList extends React.Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            count: 0,
            currentPage: 1,
            data: [],
            foodMenu: [],
            previewImage: {},
            formVisible: false,
            // 当前选中菜品
            currentFood: {},
            picPre: '',
            foodStatus: '',
            rowsData: this._getRowsData()
        };
        this.menuId = 0;
        this.columns = [{
            title: '编号',
            dataIndex: 'id',
            width: 60,
            render: text => <a>{text}</a>,
        }, {
            title: "数量",
            dataindex: 'num',
            width: 60,
            render: (text, record) => {
                return (<div><InputNumber min={0} max={100} defaultValue={text.num} onChange={(value) => {
                    let { rowsData } = this.state;
                    rowsData.numChange(text, value);
                }} /></div>);
            }
        }, {
            title: '名称',
            dataIndex: 'name',
            render: text => text
        },
        {
            title: '菜品类型',
            dataIndex: 'foodTypeList',
            render: (text, record) => {
                let foodType = [];
                text.forEach((item) => {
                    foodType.push(item.name);
                })
                return (foodType.join(', '));
            }
        },
        {
            title: '价格(￥)',
            dataIndex: 'price',
            width: 100,
            render: text => text
        }, {
            title: '优惠价(￥)',
            dataIndex: 'reducedPrice',
            width: 100,
            render: text => text
        },
        {
            title: '分数',
            dataIndex: 'score',
            width: 100,
        },
        {
            title: '图片',
            dataIndex: 'images',
            width: 200,
            render: (value, record) => {
                const { picPre } = this.state;
                let imageUrl = PLACEHOLDER_IMG;
                if (value.length !== 0) {
                    const data = value[0];
                    imageUrl = picPre + '/' + data.local;
                }
                return (<div style={{ width: '100%' }}><img src={imageUrl} alt="test" width="50%" /></div>);
            }
        },
        {
            title: '菜品状态',
            dataIndex: 'status',
            width: 100,
            render: (value, record) => {

                let statusMap = {
                    'ENABLE': ['上架', ''],
                    'SELL_OUT': ['售罄', '#ff3d1c'],
                    'DISABLE': ['下架', '#b3b3b3']
                }
                return (<div style={{ color: statusMap[value][1] }}>{statusMap[value][0]}</div>);

            }
        },
        {
            title: '是否参与打折',
            dataIndex: 'allowDiscount',
            width: 120,
            render: (value, record) => {
                return <Switch checked={value} disabled checkedChildren="是" unCheckedChildren="否" />

            }
        }
        ];
    }

    _getRowsData = () => {
        let obj = {};
        obj.id = 0;
        obj.rows = [];
        obj.number = 0;
        obj.picPre = null;
        obj.name = null;
        obj.images = [];
        obj.price = 0;
        obj.reducedPrice = 0;
        obj.status = null;
        obj.init = function (jsonData) {
            let setmeal = jsonData.setmeal;
            if (setmeal.id === null) {
                let data = setmeal.items;
                for (let i in data) {
                    if (data[i] === 0)
                        continue;
                    else {
                        data[i].num = 1;
                        obj.rows.push(data[i]);
                        obj.number++;
                        obj.num = 1;
                        obj.price += data[i].price;
                        obj.reducedPrice += data[i].reducedPrice;
                    }
                }
            } else {
                let { items } = setmeal;

                for (let i in items) {
                    let food = items[i].food;
                    food.num = items[i].num;
                    food.joinID = items[i].id;
                    food.key = items[i].id;
                    obj.rows.push(food);
                }
                obj.id = setmeal.id;
                obj.number = setmeal.items.length;
                obj.name = setmeal.name;
                obj.price = setmeal.price;
                obj.reducedPrice = setmeal.reducedPrice;
                obj.status = setmeal.status;
                obj.allowSingle = setmeal.singleDiscount;
                obj.allowDiscount = setmeal.allowDiscount;
                obj.images = setmeal.images;
            }
            obj.picPre = jsonData.picPre;
            obj.retain();
        }
        obj.initBySetMealInfo = function (jsonData) {
        }

        obj.addRow = function (rowData) {
            obj.rows.push(rowData);
            obj.number++;
        }
        obj.removeRow = function (rowData) {
            for (let i in obj.rows) {
                if (obj.rows[i].id === rowData.id) {
                    obj.rows[i] = 0;
                    obj.number--;
                }
            }
        }
        obj.numChange = function (rowData, num) {
            let rows = obj.rows;
            for (let i in rows) {
                if (rows[i] !== 0) {
                    if (rows[i].id === rowData.id)
                        if (rows[i].num > num) {
                            let t_num = rows[i].num - num;
                            rows[i].num -= t_num;
                            obj.price -= rows[i].price * t_num;
                            obj.reducedPrice -= rows[i].reducedPrice * t_num;
                            break;
                        } else if (rows[i].num < num) {
                            let t_num = num - rows[i].num;
                            rows[i].num += t_num;
                            obj.price += rows[i].price * t_num;
                            obj.reducedPrice += rows[i].reducedPrice * t_num;
                            break;
                        }
                }
            }
            obj.retain();
        }
        obj.retain = function () {
            obj.price = parseFloat(obj.price.toFixed(2));
            obj.reducedPrice = parseFloat(obj.reducedPrice.toFixed(2));
        }
        obj.getFoodList = function () {
            let foodList = [];
            let rows = obj.rows;
            for (let i in rows) {
                let join = {};
                if (rows[i].joinID)
                    join.id = rows[i].joinID;
                if (rows[i].id) {
                    let food = {};
                    food.id = rows[i].id;
                    join.food = food;
                }
                join.num = rows[i].num;
                foodList.push(join);
            }
            return foodList;
        }
        return obj;
    };

    handleCancel = () => {
        this.setState({
            formVisible: false
        })
    }

    componentDidMount() {
        let { rowsData } = this.state;
        const { router } = this.props;

        let jsonData = JSON.parse(localStorage.getItem("setmealInfo"));
        if (!jsonData) {
            router.push('/app/food/foodMenu');
            return;
        }
        // console.log(jsonData);
        rowsData.init(jsonData);
        this.setState({ count: rowsData.number, data: rowsData.rows, picPre: rowsData.picPre });
    }

    onChange(value) {
    }

    modalActivit = () => {
        let { formVisible } = this.state;
        formVisible = true;
        this.setState({ formVisible });
    }

    getFoodById = (id) => {
        return get('/food/item/' + id);
    }


    render() {
        const { foodTypeList, previewImage, formVisible, currentFood, picPre, rowsData } = this.state;
        return (
            <div className="content-container">
                <Button style={{ width: 120 }} type="primary" onClick={this.modalActivit}>{rowsData.id === 0 ? '生成套餐' : '修改套餐'}</Button>
                <div className="space-bar"></div>
                <Table columns={this.columns} dataSource={this.state.data} pagination={
                    {
                        total: this.state.count,
                        defaultPageSize: DEFAULT_SIZE,
                        current: this.state.currentPage
                    }
                }
                    scroll={{ x: 1200 }}
                />
                <Modal title="添加套餐" visible={formVisible} footer={null} onCancel={this.handleCancel}>
                    <SetMealForm rowsData={rowsData} router={this.props.router} picPre={picPre}/>
                </Modal>
            </div>
        );
    }
}

const mapStateToProps = state => {
    const { auth = { data: {} } } = state.httpData;
    return { auth };
};

export default SelectFoodList;
